package com.echovin.esb.gateway.filter;

import com.echovin.esb.gateway.constants.ErrorCode;
import com.echovin.esb.gateway.constants.OrderConstants;
import com.echovin.esb.gateway.exception.OpenException;
import com.echovin.esb.gateway.locator.GatewayIPLimitResourceLocator;
import com.echovin.esb.gateway.util.ReactiveWebUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.OrderedGatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;

import java.net.URI;
import java.util.Collections;
import java.util.List;

/**
 * IP limit过滤器
 */
@Slf4j
@Component
public class IPLimitGatewayFilterFactory extends AbstractGatewayFilterFactory<IPLimitGatewayFilterFactory.Config> {
    private static final String DATETIME_KEY = "enable";

    @Autowired
    GatewayIPLimitResourceLocator gatewayIpLimitResourceLocator;

    public IPLimitGatewayFilterFactory() {
        super(IPLimitGatewayFilterFactory.Config.class);
    }

    @Override
    public List<String> shortcutFieldOrder() {
        return Collections.singletonList(DATETIME_KEY);
    }


    @Override
    public GatewayFilter apply(IPLimitGatewayFilterFactory.Config config) {
        return new OrderedGatewayFilter((exchange, chain) -> {
            ServerHttpRequest request = exchange.getRequest();
            URI requestUri = request.getURI();
            String remoteIpAddress = ReactiveWebUtils.getRemoteAddress(exchange);
            String origin = request.getHeaders().getOrigin();

            // ip黑名单检测
            boolean deny = gatewayIpLimitResourceLocator.matchIpBlacklist(requestUri.getPath(), remoteIpAddress);
            if (deny) {
                throw new OpenException(ErrorCode.ACCESS_DENIED_BLACK_LIMITED.getCode());
            }
            // ip白名单检测
            boolean allow = gatewayIpLimitResourceLocator.matchIpWhitelist(requestUri.getPath(), remoteIpAddress);
            if (!allow) {
                throw new OpenException(ErrorCode.ACCESS_DENIED_WHITE_LIMITED.getCode());
            }
            return chain.filter(exchange);

        }, OrderConstants.IP_LIMIT);
    }

    public static class Config {
        /**
         * 使能 key
         */
        private boolean enable;

        public boolean isEnable() {
            return enable;
        }

        public void setEnable(boolean enable) {
            this.enable = enable;
        }
    }

}
